﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Data;
using Data.implement;
using log4net.Repository.Hierarchy;
using LYWebsite.Models;
using Services.Implement;
using Services.Interface;

namespace LYWebsite.Controllers
{
    public class WeiXinController : Controller
    {
        private static readonly log4net.ILog log =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //
        // GET: /WeiXin/
        private void SetCookies(WeiXinUser user)
        {
            HttpCookie cookie = new HttpCookie("UserInfo");//初使化并设置Cookie的名称
            DateTime dt = DateTime.Now;
            TimeSpan ts = new TimeSpan(30, 0, 0, 0, 0);//过期时间为30t天
            cookie.Expires = dt.Add(ts);//设置过期时间
            cookie.Values.Add("OpenId",user.openId);
            cookie.Values.Add("city", user.city);
            cookie.Values.Add("country", user.country);
            cookie.Values.Add("headimgurl", user.headimgurl);
            cookie.Values.Add("nickname", user.nickname);
            cookie.Values.Add("province", user.province);
            cookie.Values.Add("sex", user.sex);
            Response.AppendCookie(cookie);
        }
        public ActionResult GetWeiXinUserInfo(string code = "", string state = "")
        {
            return DoGetWeiXinUserInfo(code, state,"~/Charging/InitUser/?CarId=", state);
        }

        public ActionResult Charging(string code = "", string state = "")
        {
            return DoGetWeiXinUserInfo(code, state, "~/Charging/DoCharge", state);
        }
        private ActionResult DoGetWeiXinUserInfo(string code, string state, string redirectURL, string parms)
        {
            //if (code == null)
            //    return View("~/Views/ResultView.cshtml", new ResultModel() {Description = "无权限！"});
            try
            {
                log.Info("Init service.");
                IWeixinAuthService service = new WeixinAuthService();
                string token = string.Empty;
                string openId = string.Empty;
                string errorCode = string.Empty;
                string errorMsg = string.Empty;
                log.Info("Start Get Token.");
                if (service.GetToken(code, out token, out openId, out errorCode, out errorMsg))
                {
                    log.Info("Get the token "+token+" openId "+openId+" error:"+errorCode+errorMsg);
                    if (!string.IsNullOrEmpty(errorCode))
                        return Redirect("~/Result/Exception");
                    log.Info("Start Get User");
                    WeiXinUser userInfo = service.GetUser(token, openId, out errorMsg, out errorCode);
                    
                    if (userInfo == null)
                    {
                        log.ErrorFormat("get userInfo fail, errorCode:{0}, errorMsg:{1}", errorCode, errorMsg + " OpenId:" + openId);
                        return Redirect("~/Result/Exception");
                    }
                    log.Info("user is "+User.ToString());
                    log.Info("save user");
                    Session["UserInfo"] = userInfo;
                    log.Info("save user to cookies");
                    SetCookies(userInfo);
                    log.Info("redirect to "+redirectURL);
                    return Redirect(redirectURL + state);


                }
                else
                {
                    return Redirect("~/Result/ErrorInfo");

                }
            }
            catch (Exception)
            {
                log.Error("DoGetWeiXinUserInfo has exceptions. Code:"+code+" State:"+state+" Url"+redirectURL);
                return Redirect("~/Result/Exception");
            }
            

        }



        //public ActionResult Index()
        //{
        //    return View();
        //}

        ////
        //// GET: /WeiXin/Details/5

        //public ActionResult Details(int id)
        //{
        //    return View();
        //}

        ////
        //// GET: /WeiXin/Create

        //public ActionResult Create()
        //{
        //    return View();
        //}

        ////
        //// POST: /WeiXin/Create

        //[HttpPost]
        //public ActionResult Create(FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add insert logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        ////
        //// GET: /WeiXin/Edit/5

        //public ActionResult Edit(int id)
        //{
        //    return View();
        //}

        ////
        //// POST: /WeiXin/Edit/5

        //[HttpPost]
        //public ActionResult Edit(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add update logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        ////
        //// GET: /WeiXin/Delete/5

        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        ////
        //// POST: /WeiXin/Delete/5

        //[HttpPost]
        //public ActionResult Delete(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add delete logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}
    }
}
